<template>
  <!-- 点实体组件：通过传入经纬高与样式，在地图上绘制一个点 -->
  <div style="display: none"></div>
</template>

<script setup>
// 中文注释：点实体组件
// - 职责：接收一个经纬高位置与样式，向 viewer.entities 添加点标注
// - 生命周期：挂载时创建，卸载时移除
import { inject, onMounted, onBeforeUnmount, watch, ref } from "vue";
import * as Cesium from "cesium";

const CESIUM_VIEWER_KEY = "cesiumViewer";
// 变量：注入的 viewer 引用（ref）
const viewerRef = inject(CESIUM_VIEWER_KEY, null);

// props：
// - position：位置（对象，单位：度/米），包含 lon/lat/height
// - color：点颜色（CSS 色值）
// - pixelSize：点像素大小
// - show：是否显示
const props = defineProps({
  position: { type: Object, required: true },
  color: { type: String, default: "#ff4d4f" },
  pixelSize: { type: Number, default: 10 },
  show: { type: Boolean, default: true },
});

// 变量：当前点实体引用
const entityRef = ref(null);

onMounted(() => {
  if (!viewerRef) return;
  const tryCreate = () => {
    if (!viewerRef.value) return false;
    createOrUpdate();
    return true;
  };
  if (!tryCreate()) {
    const stop = watch(() => viewerRef.value, (v) => {
      if (v) {
        createOrUpdate();
        stop();
      }
    });
  }
});

onBeforeUnmount(() => {
  const viewer = viewerRef && viewerRef.value;
  if (viewer && entityRef.value) viewer.entities.remove(entityRef.value);
  entityRef.value = null;
});

watch(() => ({ ...props }), () => createOrUpdate(), { deep: true });

// 方法：创建或更新点实体
function createOrUpdate() {
  const viewer = viewerRef && viewerRef.value;
  if (!viewer) return;
  const cartesian = Cesium.Cartesian3.fromDegrees(
    props.position.lon,
    props.position.lat,
    props.position.height ?? 0
  );
  const color = Cesium.Color.fromCssColorString(props.color);
  if (entityRef.value) {
    entityRef.value.position = cartesian;
    entityRef.value.point.color = color;
    entityRef.value.point.pixelSize = new Cesium.ConstantProperty(props.pixelSize);
    entityRef.value.show = props.show;
  } else {
    entityRef.value = viewer.entities.add({
      show: props.show,
      position: cartesian,
      point: {
        color,
        pixelSize: props.pixelSize,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 1,
      },
    });
  }
}

defineExpose({ getEntity: () => entityRef.value });
</script>

<style scoped>
</style>


